import React, { useState, useEffect, useRef } from 'react';
import {
  Form,
  Input,
  Space,
  Button,
  message,
  Modal,
  TreeSelect,
  Checkbox,
  Card,
  Row,
  Col,
  Upload,
} from 'antd';
import { LoadingOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { connect, useIntl } from 'umi';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import UploadUtil from '@/components/UploadUtil';
import request from '@/utils/request';

const { confirm } = Modal;
const apiURL = '/api/services/app/Article/';
const apiURLCate = '/api/services/app/Category/';

const ContentEdit = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [datas, setDatas] = useState<any>({});
  const [cascaderOption, setCascaderOption] = useState([]);
  const [contentEditor, setContentEditor] = useState('');
  const [fileList, setFileList] = useState([]);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    fetchCategory();
    if (props.id) {
      getData(props.id);
    }
  }, [props.id]);

  const getData = (id: number) => {
    if (id > 0) {
      request(apiURL + 'Get', {
        method: 'Get',
        params: { id },
      }).then((response) => {
        if (response && response.success) {
          const result = response.result;
          result.contents = BraftEditor.createEditorState(result.contents);
          setDatas(result);
          const fileList: any = [];
          if (result.imageUrl) {
            const pics = result.imageUrl.split(',');
            pics.forEach((element: any) => {
              const obj = {
                uid: element,
                name: element,
                response: {
                  result: element,
                },
                status: 'done',
                url: UploadUtil.ossServ + element,
              };
              fileList.push(obj);
            });
          }
          setFileList(fileList);
          formRef.current.setFieldsValue({ article: result });
        }
      });
    }
  };

  const fetchCategory = () => {
    request(apiURLCate + 'GetTreeDataAsync', {
      method: 'Get',
      params: { layout: 'article' },
    }).then((response) => {
      const resp = response.result;
      setCascaderOption(resp);
    });
  };

  const onFinish = async (values: any) => {
    let act = 'Create';
    let method = 'Post';
    if (values.article.id > 0) {
      act = 'Update';
      method = 'Put';
    }
    values.article.contents = contentEditor;

    if (fileList) {
      const pics: string[] = [];
      fileList.forEach((element: any) => {
        pics.push(element.response.result);
      });
      values.article.imageUrl = pics.toString();
    } else {
      values.article.imageUrl = datas.ImageFileName;
    }

    request(apiURL + act, {
      method,
      data: values.article,
    }).then((response) => {
      if (response.success) {
        message.success('保存成功！');
        props.fetchDatas();
      } else {
        message.error('保存错误，请联系管理员');
      }
    });
  };

  const ResetForm = () => {
    const data = {
      id: 0,
    };
    setDatas(data);
    formRef.current.resetFields();
  };

  const handleDel = () => {
    request(apiURL + 'Delete', {
      method: 'Delete',
      params: { Id: datas.id },
    }).then((response) => {
      if (response.success) {
        message.success('删除成功！');
        props.fetchDatas();
        formRef.current.resetFields();
      } else {
        message.error('删除错误，请联系管理员！');
      }
    });
  };

  const showConfirm = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        handleDel();
      },
      onCancel() {},
    });
  };

  const handleChange = (editorState: any) => {
    setContentEditor(editorState.toHTML());
  };

  const handleUpload = (info: any) => {
    if (info.file.status == 'error') {
      message.error(info.file.response.error.message);
    }
    setFileList(info.fileList);
  };

  const editorProps = {
    height: 120,
    onChange: handleChange,
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div className="ant-upload-text">{intl.formatMessage({ id: 'pages.upload' })}</div>
    </div>
  );

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };

  const layout2 = {
    labelCol: { span: 0 },
    wrapperCol: { span: 24 },
  };

  return (
    <>
      <Form {...layout} ref={formRef} onFinish={onFinish}>
        <Card
          title={intl.formatMessage({ id: 'pages.content.edit' })}
          extra={
            <Space>
              <Button type="primary" htmlType="submit" loading={loading} key="1">
                {intl.formatMessage({ id: 'pages.save' })}
              </Button>
              <Button key="2" onClick={ResetForm}>
                {intl.formatMessage({ id: 'pages.reset' })}
              </Button>
              <Button
                key="3"
                danger
                onClick={showConfirm}
                disabled={datas.id == 0 || !datas.id}
              >
                {intl.formatMessage({ id: 'pages.delete' })}
              </Button>
            </Space>
          }
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="id" name={['article', 'id']} hidden>
                <Input />
              </Form.Item>
              <Form.Item label="imageUrl" name={['article', 'imageUrl']} hidden>
                <Input />
              </Form.Item>
              <Form.Item
                name={['article', 'categoryId']}
                label={intl.formatMessage({ id: 'pages.category' })}
                rules={[{ required: true, message: intl.formatMessage({ id: 'pages.select.category' }) }]}
              >
                <TreeSelect
                  value={datas.value}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  treeData={cascaderOption}
                  placeholder={intl.formatMessage({ id: 'pages.select.category' })}
                  treeDefaultExpandAll
                />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 4 }} style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item name={['article', 'isHot']} valuePropName="checked">
                    <Checkbox>{intl.formatMessage({ id: 'pages.hot' })}</Checkbox>
                  </Form.Item>
                  <Form.Item name={['article', 'isRec']} valuePropName="checked">
                    <Checkbox>{intl.formatMessage({ id: 'pages.recommend' })}</Checkbox>
                  </Form.Item>
                  <Form.Item name={['article', 'isTop']} valuePropName="checked">
                    <Checkbox>{intl.formatMessage({ id: 'pages.top' })}</Checkbox>
                  </Form.Item>
                </Input.Group>
              </Form.Item>

              <Form.Item
                label={intl.formatMessage({ id: 'pages.title' })}
                name={['article', 'title']}
                rules={[{ required: true }]}
              >
                <Input />
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.subTitle' })} name={['article', 'subTitle']}>
                <Input placeholder={intl.formatMessage({ id: 'pages.subTitle.intro' })} />
              </Form.Item>
              <Form.Item name={['article', 'tags']} label={intl.formatMessage({ id: 'pages.tags' })}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name={['article', 'extendAttr']} label={intl.formatMessage({ id: 'pages.external.link' })}>
                <Input />
              </Form.Item>
              <Form.Item name={['article', 'summary']} label={intl.formatMessage({ id: 'pages.memo' })}>
                <Input.TextArea />
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.image' })}>
                <Upload
                  action={UploadUtil.uploadOSS}
                  headers={{
                    Authorization: UploadUtil.accessToken,
                  }}
                  data={{
                    objectId: datas.id,
                    objectName: 'Article',
                    objectField: 'ImageUrl',
                  }}
                  listType="picture-card"
                  fileList={fileList}
                  multiple={true}
                  onChange={handleUpload}
                >
                  {fileList.length >= 1 ? null : uploadButton}
                </Upload>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item {...layout2} name={['article', 'contents']}>
            <BraftEditor {...editorProps} />
          </Form.Item>
        </Card>
      </Form>
    </>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ContentEdit);
